package com.test.ssm.filter;

import com.test.ssm.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 徒有琴
 */
public class SystemFilter implements Filter {
    private String[] ignoreUrl = {"/gologin.html", "/login.html"};
    private String[] teacherUrl = {"/teacher/.*"};
    private String[] studentUrl = {"/student/.*"};


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.out.println(request.getServletPath());
        String path = request.getServletPath();
        for (String s : ignoreUrl) {//登陆直接放行，不验证
            if (s.equals(path)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        HttpSession session = request.getSession();
        if (session.getAttribute(Constants.SESSION_USER) == null) {//没登陆
            response.sendRedirect("/gologin.html");
            return;
        }
        Integer userType = (Integer) session.getAttribute(Constants.USER_TYPE);
//        if (userType == 1) {//学生
//            //遍历studentUrl ，如果studentUrl中包含当前路径，就可以放行，否则代表没权限
//
//        }
//        if (userType == 2) {//老师
//            //遍历teacherUrl ，如果遍历teacherUrl中包含当前路径，就可以放行，否则代表没权限
//
//        }
        boolean check=check(path,(userType == 1)?studentUrl:teacherUrl);
        if(check){
            filterChain.doFilter(request,response);
        }else{
            response.sendRedirect("/gologin.html");
        }
    }

    public boolean check(String path, String[] urls) {
        for (String s : urls) {
            if (path.matches(s)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
